import {
  Component,
  ComponentFactoryResolver,
  ComponentRef, Injector,
  Input,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewContainerRef,
  Output,
  EventEmitter,
} from '@angular/core';
import { TipComponent } from '../applet/tip/tip.component';
import { IntroComponent } from '../applet/intro/intro.component';
import { GridComponent } from '../applet/grid/grid.component';
import { ChartComponent } from '../applet/chart/chart.component';
import {deepClone} from "../../../utils/utils";

// 智能报表组件
const eCommerceComponent = [
  TipComponent,
  IntroComponent,
  GridComponent,
  ChartComponent,
];

@Component({
  selector: 'dynamic',
  template: `
    <div class="example-box-tool">
      <apes-dropdown [apesPlacement]="'bottomRight'" [apesTrigger]="'click'">
        <i apes-icon apesType="setting" apes-dropdown></i>
        <ul apes-menu>
          <li apes-menu-item *ngFor="let botton of componentRef['_component']['button']">
            <span (click)="moreTool(botton)">{{ botton.name }}</span>
          </li>
        </ul>
      </apes-dropdown>
    </div>
    <div  class="box-container" [class.box-container-edit]="isVisible == false">
      <ng-template #container></ng-template>
    </div>
    <ng-container *ngIf="isVisible == false">
      <edit (paramsOut)="getChildEvent($event)" (cancelOut)="getChildCancel($event)"></edit>
    </ng-container>
  `,
  styleUrls: ['./dynamic.component.scss'],
  entryComponents: [...eCommerceComponent],
})
export class DynamicComponent implements OnInit, OnDestroy {

  componentRef: ComponentRef<any>; //  加载的组件实例

  @Input() componentName: string; // 需要加载的组件名
  @Input() params: any;           // 组件传入的参数
  // @Input() metadata: any;         // 组件传入的参数
  @Input() data: any;             // 组件传入的参数

  isVisible: boolean = true;      // 设置弹出的对话窗

  @ViewChild('container', { read: ViewContainerRef,static:false })
  container: ViewContainerRef;

  @Output() dyanmicOut = new EventEmitter;

  constructor(private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
  }

  ngAfterContentInit() {
    this.loadComponent();
  }

  /**
   * 加载组件
   */
  loadComponent() {
    if (this.container) this.container.clear();

    //  获取到组件
    let __component;
    eCommerceComponent.forEach((comp) => {
      // let dynamicComp = comp;   // 初始化出动态组件，获取到 name 属性
      if (comp.name == this.componentName) {
        __component = comp;
      }
    });
    if (!__component) return;

    // 创建注入器
    const childInjector = Injector.create({
      providers: [{ provide: 'params', useValue: this.params }],
      parent: this.container.parentInjector
    });

    /* 创建组件 */
    if (this.componentRef) {
      this.componentRef.destroy();
    }

    let factory = this.resolver.resolveComponentFactory(__component); // 获取组件工厂

    this.componentRef = factory.create(childInjector);  //创建带参数的组件
    this.componentRef.instance['params'] = this.params; // 向组件传递参数
    this.container.insert(this.componentRef.hostView);  //呈现组件的视图
  }

  // 更多工具
  moreTool(botton:any) {
    const areas = this.params;
    if (botton.bot === 'delete') {                    // 删除当前小程序
      for(let i=0; i < areas.length; i++) {
          for(let j=0; j < areas[i].length ; j++) {
            if(this.data['id'] === areas[i][j]['id']) {
              areas[i].splice(j, 1);
              this.dyanmicOut.emit(areas);            // 触发父组件saveCurPosition()
            }
          }
      }
    } else if (botton.bot === 'default') {   // 编辑当前小程序
          this.isVisible = false;
    }
  }

  getChildEvent(e) {
    this.isVisible = true;
    let data:any[] = deepClone(this.componentRef.instance['columnDefs']);
    let columnDefs = [];
    data.map( item => {
      for(let i of e.columnDefs){
        if( item['field'] === i ) {
          return columnDefs.push(item);
        }
      }
    });
    setTimeout(()=>{
      this.componentRef.instance['columnDefs'] = columnDefs;
    },1000)
  }

  getChildCancel(e) {
    this.isVisible = true;
    this.dyanmicOut.emit();
    console.log('editComponent ----> cancel ' + e);
  }

  ngOnDestroy(): void {
    if (this.componentRef) {
      this.componentRef.destroy();
    }
  }
}
